package com.pfs.internal.timestamp.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;

public class PfsUtil {

	public static String mm2qq(String month) {
		int mm = Integer.parseInt(month);
		return "0" + ((mm / 3) + 1);
	}

	public static java.sql.Date get_last_date_of_month(String str) throws Exception {
		Calendar c = Formater.str2cal(str);
		c.set(Calendar.DATE, 1);
		c.add(Calendar.MONTH, 1);
		c.add(Calendar.DATE, -1);
		return Formater.cal2date(c);
	}

	public static String from_partition(String str, String type) throws Exception {
		if (StringUtils.isBlank(str))
			return null;
		Calendar c = Formater.str2cal(str);
		c.set(Calendar.DATE, 1);
		if ("M".equalsIgnoreCase(type)) {

		} else if ("Q".equalsIgnoreCase(type)) {
			int m = c.get(Calendar.MONTH);
			if (m <= Calendar.MARCH)
				c.set(Calendar.MONTH, Calendar.JANUARY);
			else if (m <= Calendar.JUNE)
				c.set(Calendar.MONTH, Calendar.APRIL);
			else if (m <= Calendar.SEPTEMBER)
				c.set(Calendar.MONTH, Calendar.JULY);
			else
				c.set(Calendar.MONTH, Calendar.OCTOBER);
		} else if ("Y".equalsIgnoreCase(type))
			c.set(Calendar.MONTH, Calendar.JANUARY);
		else
			return null;
		return (perior2partitionfrom(Formater.cal2str(c)));
	}

	public static String perior2partitionto(String period) {
		String[] arr = period.split("/");
		return (arr[2] + arr[1] + "9999999999999999");
	}

	public static String perior2partitionfrom(String period) {
		String[] arr = period.split("/");
		return (arr[2] + arr[1] + "0000000000000000");
	}

	public static String perior2yearpartitionfrom(String period) {
		String[] arr = period.split("/");
		return (arr[2] + "0000000000000000");
	}

	public static String perior2yearpartitionto(String period) {
		String[] arr = period.split("/");
		return (arr[2] + "9999999999999999");
	}

	private static boolean equal(final Object obj1, final Object obj2) {
		return obj1 == obj2 || (obj1 != null && obj1.equals(obj2));
	}

	public static boolean compare_map(Map<String, Object> para_search, Map<String, Object> old_search) {
		String key;
		for (final Entry<String, Object> entry : para_search.entrySet()) {
			key = entry.getKey();
			if (!"page".equals(key) && !equal(entry.getValue(), old_search.get(key)))
				return false;
		}
		return true;
	}

	public static String print_error(Exception ex) {
		StringBuffer sb = new StringBuffer(ex.getMessage());
		sb.append("\r\nThông tin lỗi chi tiết :");
		StackTraceElement[] ste_arr = ex.getStackTrace();
		String msg;
		for (int i = 0; i < ste_arr.length; i++) {
			msg = ste_arr[i].toString();
			if (msg.startsWith("com.pfs.tph."))
				sb.append("\r\n" + ste_arr[i].toString());
		}
		return sb.toString();
	}

	public static java.sql.Date get_months_ago(int distance) throws Exception {
		Calendar c = Calendar.getInstance();
		c.add(Calendar.MONTH, distance);
		return Formater.cal2date(c);
	}

	public static java.sql.Date StringToDate(String strDate, String formatter) throws java.text.ParseException {
		if (strDate == null) {
			return null;
		} else {
			SimpleDateFormat fm = new SimpleDateFormat(formatter);
			Date d = fm.parse(strDate);
			fm = new SimpleDateFormat("yyyy-mm-dd");
			strDate = fm.format(d);
			java.sql.Date sqlDate = java.sql.Date.valueOf(strDate);
			return sqlDate;
		}
	}

	public static Date getLastday(Date datein, String Datescope) {
		Calendar c = Calendar.getInstance();
		c.setTime(datein);
		if (Datescope.equalsIgnoreCase("M")) {
			c.set(Calendar.DATE, 1);
			c.add(Calendar.MONTH, 1);
			c.add(Calendar.DATE, -1);
		} else if (Datescope.equalsIgnoreCase("Q")) {
			int m = c.get(Calendar.MONTH);
			if (m <= Calendar.MARCH)
				c.set(Calendar.MONTH, Calendar.MARCH);
			else if (m <= Calendar.JUNE)
				c.set(Calendar.MONTH, Calendar.JUNE);
			else if (m <= Calendar.SEPTEMBER)
				c.set(Calendar.MONTH, Calendar.SEPTEMBER);
			else
				c.set(Calendar.MONTH, Calendar.DECEMBER);
			c.set(Calendar.DATE, 1);
			c.add(Calendar.MONTH, 1);
			c.add(Calendar.DATE, -1);
		} else if (Datescope.equalsIgnoreCase("Y")) {
			c.set(Calendar.DATE, 31);
			c.set(Calendar.MONTH, Calendar.DECEMBER);
		} else
			return null;
		Date returnDate = new Date(c.getTime().getTime());
		return returnDate;
	}

	public static Date getFirstday(Date datein, String Datescope) {
		Calendar c = Calendar.getInstance();
		c.setTime(datein);
		if (Datescope.equalsIgnoreCase("M"))
			c.set(Calendar.DATE, 1);
		else if (Datescope.equalsIgnoreCase("Q")) {
			int m = c.get(Calendar.MONTH);
			if (m <= Calendar.MARCH)
				c.set(Calendar.MONTH, Calendar.JANUARY);
			else if (m <= Calendar.JUNE)
				c.set(Calendar.MONTH, Calendar.APRIL);
			else if (m <= Calendar.SEPTEMBER)
				c.set(Calendar.MONTH, Calendar.JULY);
			else
				c.set(Calendar.MONTH, Calendar.OCTOBER);
			c.set(Calendar.DATE, 1);
		} else if (Datescope.equalsIgnoreCase("Y")) {
			c.set(Calendar.DATE, 1);
			c.set(Calendar.MONTH, Calendar.JANUARY);
		} else
			return null;
		Date returnDate = new Date(c.getTime().getTime());
		return returnDate;
	}

	public static int get_max_day_in_month(String date_in) {
		int year = Integer.valueOf(date_in.substring(6)).intValue();
		int month = Integer.valueOf(date_in.substring(3, 5)).intValue() - 1;
		int date = Integer.valueOf(date_in.substring(0, 2)).intValue();
		Calendar calendar = Calendar.getInstance();
		calendar.set(year, month, date);
		return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
	}

	public static String get_quarter_from_date(String dateIn) {
		String re = "Quý ";
		int month = Integer.valueOf(dateIn.substring(3, 5)).intValue();
		int year = Integer.valueOf(dateIn.substring(6)).intValue();
		if (month >= 1 && month <= 3) {
			re += "1 / ";
		} else if (month >= 4 && month <= 6) {
			re += "2 / ";
		} else if (month >= 7 && month <= 9) {
			re += "3 / ";
		} else if (month >= 10 && month <= 12) {
			re += "4 / ";
		}
		re += year;
		return re;
	}

	public static String shiftLeftString(String orgStr, String inStr) {
		String ret = new String();
		int step = inStr.length();
		int len = orgStr.length();
		if (step > orgStr.length()) {
			return inStr;
		}
		ret = orgStr.substring(0, len - step) + inStr;
		return ret;
	}

	public static String getPartitionTaxo(String ma_cqt) {
		return ma_cqt.substring(0, 3) + "00";
	}

	public static String getSysDateStr() throws Exception {
		Calendar calendar = Calendar.getInstance();
		String ret = Formater.cal2str(calendar);
		return ret;
	}

	public static boolean validTinStruct(String tin) {
		return true;
	}

	public static int compareStrDate(String strDate1, String strDate2) throws ParseException {
		SimpleDateFormat fm = new SimpleDateFormat("dd/MM/yyyy");
		Date date1 = fm.parse(strDate1);
		Date date2 = fm.parse(strDate2);
		if (date1.compareTo(date2) > 0) {
			return 1;
		} else if (date1.compareTo(date2) < 0) {
			return 2;
		}
		return 0;
	}

	public static boolean compareGreatNow(String strDate) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
		Date date1 = sdf.parse(strDate);
		Calendar calendar = Calendar.getInstance();
		Calendar cal1 = Calendar.getInstance();
		cal1.setTime(date1);
		if (cal1.after(calendar))
			return true;
		return false;
	}

	public static boolean validDate(String datestr) {
		return true;
	}

	public static boolean validInteger(String strNumber) {
		int result = 0;
		try {
			result = Integer.parseInt(strNumber);
			if (result <= 0)
				return false;
		} catch (NumberFormatException ex) {
			return false;
		}
		return true;
	}

	public static String genPhanQuyenSql(String label1, String label2, String label3, String val) {
		String ret = null;
		if (StringUtils.isNotBlank(val)) {
			ret = new String(" and exists(select 1 from pnn_quyen_nsd where nsd=" + val);
		} else {
			ret = new String(" and exists(select 1 from pnn_quyen_nsd where nsd=?");
		}
		// String ret = new
		// String(" and exists(select 1 from pnn_quyen_nsd where nsd=?");
		String quyen = new String();
		if (StringUtils.isNotBlank(label1))
			quyen += "quyen=" + label1;
		if (StringUtils.isNotBlank(label2))
			if (StringUtils.isNotBlank(quyen))
				quyen += " or quyen=" + label2;
			else
				quyen += "quyen=" + label2;
		if (StringUtils.isNotBlank(label3))
			if (StringUtils.isNotBlank(quyen))
				quyen += " or quyen=" + label3;
			else
				quyen += "quyen=" + label3;
		if (StringUtils.isNotBlank(quyen))
			quyen = " and (" + quyen + ")";
		return ret + quyen + ")";
	}

	public static int getTotalPages(long records, int rows) {
		return (int) ((records % rows == 0) ? records / rows : Math.floor(records / rows) + 1);
	}

	public static String genNextId(String inStr, int len) {
		String ret = new String();
		if (StringUtils.isBlank(inStr)) {
			for (int i = 0; i < len; i++) {
				ret += '0';
			}
			return ret;
		}
		int lenStr = inStr.length();
		char[] charArrIn = new char[len];
		for (int i = 0; i < len; i++) {
			charArrIn[i] = inStr.charAt(lenStr - i - 1);
		}
		char lastChar = genNextToken(charArrIn[0]);
		ret = String.valueOf(lastChar);
		for (int i = 1; i < len; i++) {
			char tempChar;
			if (lastChar >= charArrIn[i - 1]) {
				tempChar = charArrIn[i];
			} else {
				tempChar = genNextToken(charArrIn[i]);
			}
			ret = String.valueOf(tempChar) + ret;
			lastChar = tempChar;
		}
		return ret;
	}

	public static char genNextToken(char inChar) {
		char ret = inChar;
		if (inChar >= '0' && inChar < '9') {
			ret++;
		} else if (inChar == '9') {
			ret = 'A';
		} else if (inChar >= 'A' && inChar < 'Z') {
			ret++;

		} else if (inChar == 'Z') {
			ret = '0';
		}
		return ret;
	}
	
public static boolean compare_mapBySearch(Map<String, Object> para_search, Map<String, Object> old_search) {
		
		if (para_search.size() != old_search.size())
		      return false;
		for (String key : para_search.keySet()){
			  if(!key.equals("page")){			  			  
		      if (!para_search.get(key).equals(old_search.get(key)))
		         return false;
			  }
		}
		   return true;
	}

public static String escapeSql(String str) {
        if (str == null) {
           return null;
         }
           return  StringUtils.replace(StringUtils.replace (StringUtils.replace(str, "'", "''"), "%", "\\%"), "_", "\\_");
    }

public static String  lefPadNumberPartner(Long currentNum){
	 return StringUtils.leftPad(String.valueOf(currentNum), 9, "0");
	
}
}